var chatInfo = require('../chatInfo');
var actions = require('../actions');
var $ = require('jquery');


module.exports.active = function () {
  return $.getJSON('/webim/user/get_token').then(function (data) {
    var rongCloudToken = data.result.rcToken;
    var defer = $.Deferred();
    RongIMClient.connect(rongCloudToken, {
      onSuccess: function (userId) {
        // 登录成功后从localStorage拉取未读消息
        setTimeout(function () {
          var unreadMessages = localStorage.getItem('unread_messages_' + userId);
          try {
            unreadMessages = JSON.parse(unreadMessages) || {};
            var all = [];

            for (var uid in unreadMessages) {
              if (unreadMessages[uid]) {
                all.push(unreadMessages[uid]);
              }
            }

            // 离线消息的命令消息不处理
            all = all.filter(function (message) {
              return message.messageType !== 'CommandMessage'
            });
            all.forEach(function (message) {
              receiveRongMessage(message);
            });
          } catch (e) {
            console.log('没有未读消息', e);
          }
          localStorage.setItem('unread_messages_' + userId, '');
        }, 500);
        console.log('连接成功', userId);
        defer.resolve(userId);
      },
      onTokenIncorrect: function () {
        defer.reject('连接失败,无效的TOKEN');
      },
      onError: function (errorCode) {
        console.log('连接失败', errorCode);
        defer.reject(errorCode);
      }
    });
    return defer;
  });
};

module.exports.currentUserId = function () {
  return RongIMClient.getInstance().getCurrentUserId();
};

module.exports.sendMessage = function (msg) {
  var defer = $.Deferred();
  console.log('发送消息', msg);
  var message = null;
  switch (msg.type) {
    case 'text':
      message = new RongIMLib.TextMessage({ content: msg.content, extra: '普通消息' });
      break;
    case 'image':
      message = new RongIMLib.ImageMessage({ content: '', imageUri: msg.content, extra: '普通消息' });
      break;
    case 'command':
      message = new RongIMLib.CommandMessage({ data: msg.content });
      break;
    default:
      defer.reject();
      break;
  }

  //释放发送消息的信号
  actions.sendMessage(msg);

  var msgId = msg.msgId;

  RongIMClient.getInstance().sendMessage(RongIMLib.ConversationType.PRIVATE, msg.touid, message, {
    // 发送消息成功
    onSuccess: function (message) {
      console.info("发送消息成功", message);
      localStorage.setItem('rong-msg-sent-time', message.sentTime);
      console.log('msgUID', message.messageUId, $('#msg-' + msgId));
      $('#msg-' + msgId).attr('id', 'msg-' + message.messageUId);
      defer.resolve(message);
    },
    onError: function (errorCode, message) {
      console.error('发送消息失败', errorCode, message);
      defer.reject(errorCode);
    }
  });
  return defer;
};

//断开连接
module.exports.disconnect = function () {
  RongIMClient.getInstance().logout();
  window.IMDisconnected = true;
};


// 设置连接监听状态 （ status 标识当前连接状态 ）
// 连接状态监听器
RongIMClient.setConnectionStatusListener({
  onChanged: function (status) {
    console.log('连接状态改变', status);
    actions.changeConnectionStatus(status);
    switch (status) {
      case RongIMLib.ConnectionStatus.CONNECTED:
        console.log('链接成功');
        break;
      case RongIMLib.ConnectionStatus.CONNECTING:
        console.log('正在链接');
        break;
      case RongIMLib.ConnectionStatus.DISCONNECTED:
        console.log('断开连接');
        break;
      case RongIMLib.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT:
        console.log('其他设备登录');
        break;
      case RongIMLib.ConnectionStatus.DOMAIN_INCORRECT:
        console.log('域名不正确');
        break;
      case RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE:
        console.log('网络不可用， 10秒后重新登录');
        setTimeout(function () {
          RongIMClient.reconnect();
        }, 1000);
        break;
    }

  }
});

var messageTypes = {
  TextMessage: 'text',
  ImageMessage: 'image',
  CommandMessage: 'command'
};

// 消息监听器
RongIMClient.setOnReceiveMessageListener({
  // 接收到的消息
  onReceived: receiveRongMessage
});

function receiveRongMessage(message) {
  if (message.offLineMessage) {
    return;
  }

  var content = '';
  var messageType = messageTypes[message.messageType];

  switch (message.messageType) {
    case 'TextMessage':
      content = message.content.content;
      break;
    case 'ImageMessage':
      content = message.content.imageUri || message.content.content;
      break;
    case 'CommandMessage':
      content = message.content && message.content.data;
      break;
    default:
      console.log('其他消息类型，不处理', message);
      break;
  }

  var msg = {
    type: messageType,
    content: content,
    time: message.sentTime,
    fromSuid: message.senderUserId,
    from: message.senderUserId,
    to: message.targetId,
    msgId: message.messageUId
  };

  actions.receivedMessage(msg);
  console.log('接收到消息', message);
  localStorage.setItem('rong-msg-sent-time', message.sentTime);
}
